package com.heima.media.service.impl;

import ch.qos.logback.core.joran.util.beans.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.MediaThreadLocalUtil;
import com.heima.media.dto.ContentDto;
import com.heima.media.dto.ImageDto;
import com.heima.media.dto.WmNewsDto;
import com.heima.media.dto.WmNewsPageDto;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmNewsMaterial;
import com.heima.media.mapper.WmNewsMapper;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmNewsMaterialService;
import com.heima.media.service.IWmNewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Lazy;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-03-12
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements IWmNewsService {
    @Autowired
    private IWmNewsMaterialService wmNewsMaterialService;

    @Autowired
    @Lazy
    private IAuditService auditService;
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    @Value("${topic.upDownTopic}")
    private String upDownTopic;
    public void setName(String upDownTopic)
    {
        this.upDownTopic=upDownTopic;
    }
    @Override
    public ResponseResult listByCondition(WmNewsPageDto dto) {
// 获取线程内user
        User user = MediaThreadLocalUtil.get();
// 判断是否是登录状态
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
// 构造分页条件
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
// 构造查询条件对象
        LambdaQueryWrapper<WmNews> query = new LambdaQueryWrapper<>();
        query.eq(WmNews::getUserId, user.getUserId());
// 判断关键字是否为null
        if (!StringUtils.isEmpty(dto.getKeyword())) {
            query.like(WmNews::getTitle, dto.getKeyword());
        }
        if (dto.getStatus() != null) {
            query.eq(WmNews::getStatus, dto.getStatus());
        }
        if (dto.getChannelId() != null) {
            query.eq(WmNews::getChannelId, dto.getChannelId());
        }
        if (dto.getBeginPubDate() != null) {
            query.ge(WmNews::getPublishTime, dto.getBeginPubDate());
        }
        if (dto.getEndPubDate() != null) {
            query.le(WmNews::getPublishTime, dto.getEndPubDate());
        }
// 按照发布时间降序排序
        query.orderByDesc(WmNews::getPublishTime);
// 分页查询
        IPage<WmNews> iPage = this.page(page, query);
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(),
                iPage.getTotal(), iPage.getRecords());
        return result;


    }

    @Override
    public ResponseResult submit(WmNewsDto dto) {
        User user = MediaThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
            if(dto.getId()!=null)
            {
                //删除对应的文章对应的素材类似外键，写成方法估计是为了解耦吗
                removeRelation(dto.getId());
            }
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);

        wmNews.setUserId(user.getUserId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setImages(JSON.toJSONString(dto.getImages()));
        //接下来的问题就是那个自动，因为content是个对象数组，以json的形式存储再数据库
        String content = wmNews.getContent();
        //类型为-1就是自动，就需要处理了
       List<ImageDto> contentImages=  getImagesFromContent(content);
        if (dto.getType() == -1) {
            // 判断内容图片的数量
            // 内容中无图,设置封面类型为0
            // 内容中图片数量小于3张,设置封面类型为1 并且取内容中的第一张图片作为封面
            // 内容中图片数量大于等于3,设置封面类型为3,截取内容图片的前3张作为封面
            if (contentImages.size() <= 0) {
                wmNews.setType(0);
            } else if (contentImages.size() < 3) {
                wmNews.setType(1);
                List<ImageDto> coverImages = contentImages.subList(0, 1);
                wmNews.setImages(JSON.toJSONString(coverImages));
            } else {
                wmNews.setType(3);
                List<ImageDto> coverImages = contentImages.subList(0, 3);
                wmNews.setImages(JSON.toJSONString(coverImages));
            }
        }
        //保存新闻
        saveOrUpdate(wmNews);
        if(dto.getStatus()==1){
            //如果提交审核，估计要把这些都插入道素材表，审核通过的就从素材表获取
            //保存内容图片
            List<ImageDto> coverImages = JSON.parseArray(wmNews.getImages(), ImageDto.class);
            saveRelation(contentImages,0,wmNews.getId());
            //保存封面图片
            saveRelation(coverImages,1,wmNews.getId());
            //提交审核
            auditService.audit(wmNews);
        }
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        WmNews wmNews = getById(dto.getId());
        if(wmNews==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        if(wmNews.getStatus()!=9)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        wmNews.setEnable(dto.getEnable() == 1);
        updateById(wmNews);
        String jsonString = JSON.toJSONString(wmNews);
        kafkaTemplate.send(upDownTopic,wmNews.getArticleId().toString(),wmNews.getEnable().toString());
        return ResponseResult.okResult();

    }

    private void saveRelation(List<ImageDto> contentImages, int type, Integer id) {
        int order=0;
        for (ImageDto contentImage : contentImages) {
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            wmNewsMaterial.setMaterialId(contentImage.getId());
            wmNewsMaterial.setNewsId(id);
            wmNewsMaterial.setType(type);
            wmNewsMaterial.setOrd(order++);
            wmNewsMaterialService.save(wmNewsMaterial);
        }
    }

    private List<ImageDto> getImagesFromContent(String content) {

        //content是json类型
        List<ContentDto> contentDtos = JSON.parseArray(content,ContentDto.class);
        ArrayList<ImageDto> imageDtos = new ArrayList<>();
        for (ContentDto contentDto : contentDtos) {
            if(contentDto.getType().equals("image"))
            {
                ImageDto imageDto = new ImageDto();
                //复制属性
                imageDto.setId(contentDto.getId());
                imageDto.setUrl(contentDto.getValue());
                imageDtos.add(imageDto);
            }
        }
        return imageDtos;
    }

    private void removeRelation(Integer id) {
        //删除对应的文章对应的外键
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNewsMaterial::getNewsId,id);
        wmNewsMaterialService.remove(queryWrapper);

    }

}
